import redis
import collections

_pool = redis.ConnectionPool(host='localhost', port=6379)
_r = redis.Redis(connection_pool=_pool)


def session(method):
    def wrapper(request, module, handler, func, *args, **kwargs):
        request.session.session_id = '__session_' + request.request.headers.get('session_id')
        return method(request, module, handler, func, args, kwargs)
    return wrapper


class Session(collections.UserDict):

    SESSION_TIME_OUT = 24 * 2600 * 7

    def __init__(self, session_id=None):
        super(Session, self).__init__(self)
        global _r
        self.__redis = _r
        self.session_id = session_id

    def __missing__(self, key):
        if isinstance(key, str):
            raise KeyError(key)
        return self.data[str(key)]

    def __contains__(self, key):
        return str(key) in self.data

    def __setitem__(self, key, item):
        self.data[str(key)] = item
        self.__redis.setex(name=self.session_id, value=self.data, time=Session.SESSION_TIME_OUT)

    def __getattr__(self, key):
        return self.data[str(key)]

    def __delitem__(self, key):
        if str(key) in self.data:
            del self.data[str(key)]
            self.__redis.setex(name=self.session_id, value=self.data, time=Session.SESSION_TIME_OUT)

    @property
    def session_id(self):
        return self.__session_id

    @session_id.setter
    def session_id(self, new_session_id):
        self.__session_id = new_session_id
        if new_session_id:
            dd = self.__redis.get(new_session_id)
            if dd:
                self.data = eval(dd)
            else:
                self.data = {}
            self.__redis.setex(name=self.session_id, value=self.data, time=Session.SESSION_TIME_OUT)


def redis_set(key, value):
    global _r
    if value in ['', None]:
        _r.delete(key)
    else:
        _r.set(key, value)


# time: second
def redis_set_ex(key, value, time):
    global _r
    if value in ['', None]:
        _r.delete(key)
    else:
        _r.setex(key, value, time)


def redis_get(key):
    global _r
    return _r.get(key)


def get_redis_conn():
    return _r

#
# session = Session('jjj')
# session['name'] = 'zhang'
# print(session.get('name'))
# print(session['phone'])
